------------------------------------------------------------------------------------------------------------------------------------------------
-- -- tasks base lib

local function language_change_say(theNPC)
    theNPC.CHAT_TABLE = {}
    pcall(function()
        -- theNPC.npc_base_lib:Get_Language() == "ch"
        theNPC.CHAT_TABLE = TUNING.NPC_CHAT_TABLE[ theNPC.npc_base_lib:Get_Language() ] ["npc_event_thief"] or {}
    end)
end
-------------------------------------------------------------------------------------------------------------------------------------------------
local function Time_Out_Leave(inst)
    local theNPC = inst.entity:GetParent()
    local time = theNPC.npc_base_lib:Get_Time_Out()
    if time then
        inst:DoTaskInTime(time,function()
            inst:Remove()
            theNPC:AddDebuff("npc_event_leave","npc_event_leave")
            -- theNPC.npc_base_lib:Say(theNPC.CHAT_TABLE.time_out)
            print("Warning : npc time out and leave")
        end)
    end
end

local function take_item_2_other_container(item,player)
    -- item:Remove()
    local box = TheSim:FindFirstEntityWithTag("npc_item_thief_box")
    if box == nil then
        local portal_door = TheSim:FindFirstEntityWithTag("multiplayer_portal")
        if portal_door == nil then
            return false
        end
        local x,y,z = portal_door.Transform:GetWorldPosition()
        box = SpawnPrefab("npc_item_thief_box")
        box.Transform:SetPosition(x, 0, z)
    end
    if box == nil then
        return false
    end
    player.components.inventory:DropItem(item,true,true)
    box.components.container:GiveItem(item)
    return true
end

local function Stealing_item(theNPC)
    local theplayer = theNPC.npc_base_lib:Get_Linked_Player()
    if theplayer == nil or theplayer.components.inventory == nil then
        return
    end

    theNPC.stealling_tar_item_table = {}
    local itemCheckFn = function(item,theNPC)
        local function band_check(theItemName_str)
            local Whitelist = {"eyebone","debugstone","name"}
            local ret = false
            for i ,iName in pairs(Whitelist) do
                if string.find(theItemName_str,iName) ~= nil then
                    ret = true
                    break
                end

            end
            return ret
        end 

        if item and item:IsValid() then
            if item:HasTag("nosteal") or item:HasTag("irreplaceable") then
                return
            end

            if band_check(item.prefab) == true then
                return
            end

            if item.components.container or item.components.inventory then
                return
            end

            if theNPC.stealling_tar_item_table then
                table.insert(theNPC.stealling_tar_item_table,item)
            end
        end
    end

    local slot = theplayer.components.inventory.itemslots
    theplayer.components.inventory:ForEachItem(itemCheckFn,theNPC)

    -- print("stealling_tar_item_table +++++++++++++++++++ ")
    -- for k, v in pairs(theNPC.stealling_tar_item_table) do
    --     print(k,v)
    -- end
    if #theNPC.stealling_tar_item_table >= 1 then
        local ret = theNPC.npc_base_lib:GetRandom(theNPC.stealling_tar_item_table)
        if ret and type(ret) == "table" and ret.Remove then
            theNPC:DoTaskInTime(2,function()
                -- TheNet:Announce(theNPC.CHAT_TABLE.Announce_succeed)
                theplayer.npc_base_lib:Wisper(string.gsub(theNPC.CHAT_TABLE.Announce_succeed,"XXXXXXX",ret:GetAdjectivedName()))
            end)
            -- ret:Remove()
            if take_item_2_other_container(ret,theplayer) ~= true then    --- 找不到合适的位置放置，则删除物品
                ret:Remove()
            end

            return true
        end
    end

    if theplayer.components.sanity then
        theNPC:DoTaskInTime(2,function()
            -- TheNet:Announce(theNPC.CHAT_TABLE.Announce_failed)   
            theplayer.npc_base_lib:Wisper(theNPC.CHAT_TABLE.Announce_failed)            
        end)
        theplayer.components.sanity:SetPercent(0)
    end
    return false
end

local function LeaveItemEQ(theNPC)
    -- local temp_table = theNPC.npc_base_lib:Get_Equipments_Hand()
    -- local ret_name = theNPC.npc_base_lib:GetRandom(temp_table) or "cane"
    -- local weapon = SpawnPrefab(ret_name)
    -- weapon.components.equippable.walkspeedmult = 2
    -- theNPC.npc_base_lib:Equip(weapon)
    if theNPC.components.locomotor then
        theNPC.components.locomotor.runspeed = TUNING.WILSON_RUN_SPEED*1.6
    end
end

local function NPC_TASKS_INIT(inst)
    local theNPC = inst.entity:GetParent()
    language_change_say(theNPC)
    Time_Out_Leave(inst)
    -- local  theplayer = theNPC.TheLinkPlayer
    -- theNPC.NPC_BASE_LIB:giveNpcHat(theNPC)
    theNPC.npc_base_lib:Equip_Random_Hat()
    theNPC.npc_base_lib:Equip_Random_Cloth()
    theNPC.npc_base_lib:Equip_Random_Weapon()
    theNPC:AddTag("INLIMBO")
    theNPC:AddTag("notarget")
    theNPC:AddTag("noattack")
    theNPC:AddTag("invisible")
    theNPC:AddTag("Unable_To_Refuse")
    theNPC.npc_event = inst.prefab
end

local function NPC_TASKS(inst)
    local theNPC = inst.entity:GetParent()
    if TheWorld.state.isnight  or TheWorld:HasTag("cave") then
        theNPC.npc_base_lib:Try_2_Set_Light(true)
    else
        theNPC.npc_base_lib:Try_2_Set_Light(false)
    end
    local theplayer = theNPC.__link_player
    if theplayer == nil or theplayer:IsValid() == false then
        -- theNPC:RemoveDebuff(inst.prefab)
        inst:Remove()
        theNPC:AddDebuff("npc_event_leave","npc_event_leave")
        print("Warning : theNPC.__link_player == nil")
        return
    end

    if theNPC.event_step == nil then

        if theNPC.npc_base_lib:Close_2_Target_In_Range({range = 3}) == true then
            theNPC.event_step = 1
        end
        
    elseif theNPC.event_step == 1 then

        theNPC.npc_base_lib:FaceToInst()
        theNPC.npc_base_lib:Action_Give()
        if Stealing_item(theNPC) == true then
            print("Stealing_item SUCCEED")
        end
        theNPC.event_step = theNPC.event_step + 1

    elseif theNPC.event_step == 2 then       
        theNPC.event_step = theNPC.event_step + 1

    elseif theNPC.event_step == 3 then       
        theNPC.event_step = theNPC.event_step + 1
        
    elseif theNPC.event_step == 4 then
        -- theNPC.event_step = theNPC.event_step + 1
        -- theNPC:RemoveDebuff(inst.prefab)
        inst:Remove()
        LeaveItemEQ(theNPC)
        theNPC.npc_base_lib:Say(theNPC.CHAT_TABLE.hahaha)
        theNPC:AddDebuff("npc_event_leave","npc_event_leave")
    end
end
--------------------------------------------------------------------------------------------------------------------------------------------------

local function OnAttached(inst,target) -- when the debuff on or player is newSpawn(or through the cave)
    inst.entity:SetParent(target.entity)
    inst.Network:SetClassifiedTarget(target)
    local NPC = inst.entity:GetParent()
    local flag ,error_code= pcall(function(inst,target)
        if TheWorld.ismastersim then

            NPC_TASKS_INIT(inst)


        end
    end,inst,target)
    if flag == false  then
        print("Error : OnAttached(inst,target) ",inst.prefab)
        print(error_code)
        NPC:Remove()
    end
end

local function OnDetached(inst) -- When eliminating from the outside
    local player = inst.entity:GetParent()   
    -- print(" FROM OUSIDE REMOVE ")
    
    -- inst:Remove()
end

local function ExtendDebuff(inst)
    -- inst.countdown = 3 + (inst._level:value() < CONTROL_LEVEL and EXTEND_TICKS or math.floor(TUNING.STALKER_MINDCONTROL_DURATION / FRAMES + .5))
end



local function OnUpdate(inst,ismastersim)
    local NPC = inst.entity:GetParent()
    local flag,error_code = pcall(function(inst,ismastersim)
        -- local NPC = inst.entity:GetParent()

        NPC_TASKS(inst)


    end,inst,ismastersim)
    if flag == false then
        print("Error : OnUpdate(inst,ismastersim) ,step:",NPC.event_step ,inst.prefab)
        print(error_code)
        NPC:Remove()
    end
end

local function fn()
    local inst = CreateEntity()

    inst.entity:AddTransform()
    inst.entity:AddNetwork()

    inst:AddTag("CLASSIFIED")


    -- inst:DoPeriodicTask(1, OnUpdate, nil, TheWorld.ismastersim)  -- in one seconds
    inst:DoPeriodicTask( 0.5, OnUpdate, nil, TheWorld.ismastersim)  -- in 0.5 seconds

    inst.entity:SetPristine()

    if not TheWorld.ismastersim then
        return inst
    end

    inst:AddComponent("debuff")
    inst.components.debuff:SetAttachedFn(OnAttached)
    inst.components.debuff.keepondespawn = false -- 是否保持debuff 到下次登陆
    -- inst.components.debuff:SetDetachedFn(inst.Remove)
    inst.components.debuff:SetDetachedFn(OnDetached)
    -- inst.components.debuff:SetExtendedFn(ExtendDebuff)
    -- ExtendDebuff(inst)


    return inst
end

return Prefab("npc_event_thief", fn)
